//
//  KALoginVC.swift
//  kano
//
//  Created by Sophia on 2024/8/14.
//

import UIKit
import SnapKit
import RxCocoa
import RxSwift
import ActiveLabel
import PopupDialog
import WebKit

class KALoginVC: KABaseVC, WKNavigationDelegate {
    private let disposeBag = DisposeBag()
    
    lazy var draggableButton: UIButton = {
        let button = UIButton(type: .system)
        button.setBackgroundImage(UIImage(named: "machine_ser"), for: .normal)
        button.frame = CGRect(x: var_screenWidth-kscale(36), y: kscale(600), width: kscale(36), height: kscale(28)) // 初始位置
        button.addTarget(self, action: #selector(serviceClick(_:)), for: .touchUpInside)
        return button
    }()
    
    @objc func serviceClick(_ sender: UIButton) {
        sender.preventDoubleTap()
        KAFlutterManager.showFlutterVC(route: "/onlineService", parameter: ["mobile" : KAUserManager.shared.user.mobile, "version" : KAUserManager.ka_appVersion()])
//        KAFlutterManager.showFlutterVC(route: "/onlineSocket", parameter: ["mobile" : KAUserManager.shared.user.mobile])
    }

    lazy var var_bgView: UIImageView = {
        let var_bgView = UIImageView(frame: CGRectMake(0, 0, var_screenWidth, var_screenHeight))
        var_bgView.image = UIImage(named: "login_bg")
        return var_bgView
    }()
    
//    lazy var var_greetingView: UIImageView = {
//        let x = (var_screenWidth-kscale(229))/2
//        let var_greetingView = UIImageView(frame: CGRectMake(x, UIDevice.ka_fullNavHeight+kscale(16), kscale(229), kscale(64)))
//        var_greetingView.image = UIImage(named: "login_greeting")
//        return var_greetingView
//    }()
    lazy var var_greetingView: UILabel = {
        let var_greetingView = UILabel()
        let x = (var_screenWidth-kscale(229))/2
        var_greetingView.frame = CGRectMake(x, UIDevice.ka_fullNavHeight+kscale(16), kscale(229), kscale(64))
        var_greetingView.font = UIFont.systemFont(ofSize: kscale(24), weight: .bold)
        var_greetingView.textAlignment = .center
        var_greetingView.textColor = .white
        var_greetingView.numberOfLines = 2
        var_greetingView.text = "Hi,Welcome to\nLendSafe"
        return var_greetingView
    }()
    
    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = UIColor.white
        var_cornerView.layer.cornerRadius = kscale(30)
        var_cornerView.layer.masksToBounds = true
        var_cornerView.frame = CGRectMake(kscale(20), UIDevice.ka_fullNavHeight+kscale(140), var_screenWidth-kscale(40), kscale(330))
        return var_cornerView
    }()
    
    lazy var var_appView: UIImageView = {
        let var_appView = UIImageView(image: UIImage(named: "login_appIcon"))
        var_appView.size = CGSize(width: kscale(88), height: kscale(88))
        var_appView.centerX = var_cornerView.centerX
        var_appView.y = var_cornerView.y - kscale(44)
        return var_appView
    }()
    
    lazy var var_mobileLabel: UILabel = {
        let var_mobileLabel = UILabel()
        var_mobileLabel.x = kscale(20)
        var_mobileLabel.y = kscale(80)
        var_mobileLabel.width = var_cornerView.width-kscale(40)
        var_mobileLabel.height = kscale(20)
        var_mobileLabel.font = UIFont.systemFont(ofSize: kscale(16), weight: .bold)
        var_mobileLabel.textColor = .black
        var_mobileLabel.text = "Mobile number"
        return var_mobileLabel
    }()
    
    lazy var var_mobileView: KAInputView = {
        var_mobileView = KAInputView(showLeftView: true)
        var_mobileView.x = kscale(20)
        var_mobileView.y = var_mobileLabel.bottom + kscale(8)
        var_mobileView.size = CGSizeMake(var_cornerView.width-kscale(40), kscale(48))
        return var_mobileView
    }()
    
    lazy var var_signBtn: UIButton = {
        let var_signBtn = UIButton(frame: CGRectMake(kscale(48), var_mobileView.bottom+kscale(32), var_cornerView.width-kscale(96), kscale(50.0)))
        var_signBtn.setTitle("SignUp/Login", for: .normal)
        var_signBtn.setTitleColor(.white, for: .normal)
        var_signBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_signBtn.backgroundColor = .colorBDBDF5
        var_signBtn.layer.cornerRadius = kscale(25)
        var_signBtn.layer.masksToBounds = true
        var_signBtn.addTarget(self, action: #selector(ka_signButtonClick), for: .touchUpInside)
        return var_signBtn
    }()
    
    lazy var var_checkBox: UIButton = {
        let var_checkBox = UIButton(frame: CGRectMake(kscale(20), var_signBtn.bottom+kscale(16), kscale(16), kscale(16)))
        var_checkBox.setImage(UIImage(named: "checkbox_unsel"), for: .normal)
        var_checkBox.setImage(UIImage(named: "checkbox_sel"), for: .selected)
        return var_checkBox
    }()
    
    lazy var protocolLabel: ActiveLabel = {
        protocolLabel = ActiveLabel()
        let customType = ActiveType.custom(pattern: "Privacy Policy")
        let customType1 = ActiveType.custom(pattern: "Loan Terms")
        protocolLabel.enabledTypes = [customType, customType1]
        protocolLabel.numberOfLines = 0
        protocolLabel.text = "I have read and accept Privacy Policy, Loan Terms."
        protocolLabel.lineSpacing = kscale(8);
        protocolLabel.font = kFontSize(12)
        protocolLabel.customColor[customType] = .themeColor
        protocolLabel.customColor[customType1] = .themeColor
        protocolLabel.textColor = .color8A8891
        protocolLabel.handleCustomTap(for: customType, handler: { (customType) in
            //docx html
            if let filePath = Bundle.main.path(forResource: "privacy", ofType: "html") {
                let fileURL = URL(fileURLWithPath: filePath)
                let webVC = KAWebVC.init(title: "Privacy Policy", url: fileURL)
                self.navigationController?.pushViewController(webVC, animated: true)
            }
        })
        protocolLabel.handleCustomTap(for: customType1, handler: { (customType) in
            if let filePath = Bundle.main.path(forResource: "loanTerms", ofType: "html") {
                let fileURL = URL(fileURLWithPath: filePath)
                let webVC = KAWebVC.init(title: "Loan Terms", url: fileURL)
                self.navigationController?.pushViewController(webVC, animated: true)
            }
        })
        protocolLabel.frame = CGRect.init(x: var_checkBox.right+8, y: var_checkBox.top, width: var_cornerView.width-kscale(64), height: kscale(16))
        return protocolLabel
    }()
}

extension KALoginVC {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_setUI()
        ka_bindUI()
    }
    
    func ka_setUI() {
        view.backgroundColor = .purple
        var_hiddenNavigationBar = true
        
        view.addSubview(var_bgView)
        view.addSubview(var_greetingView)
        view.addSubview(var_cornerView)
        view.addSubview(var_appView)
        var_cornerView.addSubview(var_mobileLabel)
        var_cornerView.addSubview(var_mobileView)
        var_cornerView.addSubview(var_signBtn)
        var_cornerView.addSubview(var_checkBox)
        var_cornerView.addSubview(protocolLabel)
        
        view.addSubview(draggableButton)
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
        draggableButton.addGestureRecognizer(panGesture)
    }
    
    @objc func handlePanGesture(_ sender: UIPanGestureRecognizer) {
        let translation = sender.translation(in: view)
        if let button = sender.view {
            let newY = button.center.y + translation.y
            button.center = CGPoint(x: button.center.x, y: newY)
        }
        sender.setTranslation(.zero, in: view)
        if sender.state == .ended {
            print("Button moved to vertical position: \(sender.view?.center.y ?? 0)")
        }
    }
    
    func ka_bindUI() {
        var_mobileView.contentTF.rx.text
            .orEmpty
            .map { text in
                if text.count == 10, !text.hasPrefix("0") {
                    return .themeColor
                }
                return text.count < 11 ? .colorBDBDF5 : .themeColor
            }
            .bind(to: var_signBtn.rx.backgroundColor)
            .disposed(by: disposeBag)
        
        var_checkBox.rx.tap
            .subscribe(onNext: { [weak self] in
                self!.var_checkBox.isSelected = !self!.var_checkBox.isSelected
            })
            .disposed(by: disposeBag)
    }
    
    @objc func ka_signButtonClick() {
  
        guard var_mobileView.contentTF.text!.correctNumber().verifyPhone else {
            return view.makeToast("Please enter the correct phone number")
        }
        guard var_checkBox.isSelected else {
            view.endEditing(true)
            let message = "Thank you for using LendSafe. Before using LendSafe, please read Privacy Policy to understand how we collect, use and store your data to understand the responsibilities and obligations of each party, and other detailed information.If you agree, you can turn on our service. If you choose to decline, we will not be able to serve you."
            let alert = KAAlertView.alert(withTitle: "", subtitle: message, clickTitle: "Privacy Policy", clickSecond: "") { clickedTitle in
                print("Clicked title: \(clickedTitle)")
                if clickedTitle.contains("Privacy Policy") {
                    if let filePath = Bundle.main.path(forResource: "privacy", ofType: "html") {
                        let fileURL = URL(fileURLWithPath: filePath)
                        let webVC = KAWebVC.init(title: "Privacy Policy", url: fileURL)
                        self.navigationController?.pushViewController(webVC, animated: true)
                    }
                }
            }
            alert.addAction(KAAlertAction(title: "Refused", titleColor: .black, backgroundColor: .clear) { action in
                print("Refused button clicked")
                
            })
            alert.addAction(KAAlertAction(title: "I have read and accept", titleColor: .blue, backgroundColor: .clear) { [self] action in
                print("OK button clicked")
                var_checkBox.isSelected = true
                ka_checkMobile()
            })
            alert.show()
            return
        }
        ka_checkMobile()
    }
    //校验手机号
    func ka_checkMobile() {
        NetService.ka_checkMobileWith(mobile: var_mobileView.contentTF.text!.correctNumber()) { [self] isSuccess, message, response in
            if isSuccess {
                guard let user = response?.content else { return }
                let defaultUser = KAUserManager.shared.user
                var newUser = defaultUser.merge(with: user)
                newUser.mobile = var_mobileView.contentTF.text!.correctNumber()
                KAUserManager.shared.user = newUser
                if newUser.haveregistered {
                    //注册页面验证为老用户
                    KAAFTool.logEvent(event: "SKP_ExistingRegistration_old")

                    let vc = KAInputPwdVC()
                    vc.codeToken = newUser.codeToken
                    vc.logoutStatus = newUser.logoutStatus
                    self.navigationController?.pushViewController(vc, animated: true)
                } else {
                    //注册页面验证为新用户
                    KAAFTool.logEvent(event: "SKP_ExistingRegistration_new")

                    let vc = KAOTPVC()
                    vc.operationType = .Register
                    vc.mobileCodeToken = newUser.codeToken
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
        }
    }
}


